//
//  MainViewController.swift
//  Zayl--weibo
//
//  Created by 张玉 on 15/9/6.
//  Copyright © 2015年 ZY. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        NSThread.sleepForTimeInterval(3.0)//延长3秒

       addChildViewControllers()
    
}
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 此时 tabBarButton 都已经创建
        setupComposedButton()
    }
    
     /// 设置撰写按钮位置
    private func setupComposedButton() {
        let w = tabBar.bounds.width / CGFloat(viewControllers!.count)
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.frame.height)
        
        composeButton.frame = CGRectOffset(rect, 2 * w, 0)
        
    }
    
    func clickComposedButton() {
       print("我被点击了")
    }

    private func addChildViewControllers() {
        // 只是添加控制器，并没有创建 tabBar 的 button
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(UIViewController())
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
        
        

        
        
    }
   
    private func addChildViewController(vc:UIViewController, title:String, imageName:String) {
        
        tabBar.tintColor = UIColor.purpleColor()
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
        
        
    }

    //  懒加载控件
    private lazy var composeButton:UIButton = {
        //自定义类型按钮
        let btn = UIButton()
    
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        
        self.tabBar.addSubview(btn)
        
        btn.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
        
    }()
    
}
